package com.example.shangjiba;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

public class MineFragment extends Fragment {

    private TextView tvUsernameDisplay;
    private TextView tvInterest;
    private Button btnSelectInterest;
    private Button btnMyBooks;
    private Button btnLogout;
    private SharedPreferences sharedPreferences;
    private ActivityResultLauncher<Intent> interestLauncher;
    private BroadcastReceiver interestReceiver;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        
        tvUsernameDisplay = view.findViewById(R.id.tv_username_display);
        tvInterest = view.findViewById(R.id.tv_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnMyBooks = view.findViewById(R.id.btn_my_books);
        btnLogout = view.findViewById(R.id.btn_logout);
        
        sharedPreferences = requireActivity().getSharedPreferences("UserData", Context.MODE_PRIVATE);
        
        // 注册ActivityResultLauncher用于接收兴趣选择结果
        interestLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == android.app.Activity.RESULT_OK && result.getData() != null) {
                    String interest = result.getData().getStringExtra("interest");
                    if (interest != null && !interest.isEmpty()) {
                        // 保存兴趣到SharedPreferences
                        sharedPreferences.edit().putString("interest", interest).apply();
                        tvInterest.setText("当前兴趣：" + interest);
                        
                        // 发送广播通知HomeFragment更新
                        Intent broadcastIntent = new Intent("com.example.shangjiba.INTEREST_UPDATED");
                        requireActivity().sendBroadcast(broadcastIntent);
                    }
                }
            }
        );
        
        // 加载并显示用户信息
        loadUserInfo();
        
        // 选择兴趣按钮
        btnSelectInterest.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), InterestSelectActivity.class);
            interestLauncher.launch(intent);
        });
        
        // 我的书籍按钮
        btnMyBooks.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), BookListActivity.class);
            startActivity(intent);
        });
        
        // 退出登录按钮
        btnLogout.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
            builder.setTitle("确认退出")
                    .setMessage("是否确认退出登录？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 清除用户数据
                        sharedPreferences.edit().clear().apply();
                        
                        // 返回登录页
                        Intent loginIntent = new Intent(requireActivity(), LoginActivity.class);
                        loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(loginIntent);
                        requireActivity().finish();
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .show();
        });
        
        // 注册广播接收器，监听兴趣变化
        interestReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                loadUserInfo();
            }
        };
        
        IntentFilter filter = new IntentFilter("com.example.shangjiba.INTEREST_UPDATED");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            requireActivity().registerReceiver(interestReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            requireActivity().registerReceiver(interestReceiver, filter);
        }
        
        return view;
    }

    private void loadUserInfo() {
        String username = sharedPreferences.getString("username", "");
        String interest = sharedPreferences.getString("interest", "未选择");
        
        if (interest.isEmpty()) {
            interest = "未选择";
        }
        
        tvUsernameDisplay.setText("用户邮箱：" + username);
        tvInterest.setText("当前兴趣：" + interest);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次回到前台时更新用户信息
        loadUserInfo();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 注销广播接收器
        if (interestReceiver != null) {
            requireActivity().unregisterReceiver(interestReceiver);
        }
    }
}
